package controller

import (
	"blog_server/global"
	"blog_server/internal/service"
	"blog_server/pkg/app"
	"blog_server/pkg/errcode"
	"github.com/gin-gonic/gin"
)

type FileController struct{}

func NewFileController() FileController {
	return FileController{}
}

func (fc *FileController) UploadFile(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c.Request.Context())
	fileHeader, err := c.FormFile("file")
	if err != nil {
		global.Logger.Errorf("c.FormFile err: %v", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	err = svc.UploadFileToOSS(fileHeader)
	if err != nil {
		global.Logger.Errorf("svc.UploadFileToOSS err: %v", err)
		response.ToErrorResponse(errcode.ServerError)
		return
	}
	response.ToSuccessResponse(nil)
}

func (fc *FileController) GetImgList(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c.Request.Context())
	imgList, err := svc.GetImgList()
	if err != nil {
		global.Logger.Errorf("svc.GetImgList err: %v", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	response.ToSuccessResponse(gin.H{"list": imgList})
}

func (fc *FileController) DelImg(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c.Request.Context())
	fileName := c.Param("fileName")
	err := svc.DelImg(fileName)
	if err != nil {
		global.Logger.Errorf("svc.GetImgList err: %v", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	response.ToSuccessResponse(nil)
}
